package com.mh.service;

import com.mh.config.AiRecorderConfig;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;

import java.util.HashMap;
import java.util.Map;

/**
 * AI-Recorder服务类：调用AI接口解析记账文本
 */
@Service
public class AiRecorderService {
    private final WebClient webClient;
    private final AiRecorderConfig aiRecorderConfig;

    // 构造函数注入配置和WebClient
    public AiRecorderService(AiRecorderConfig aiRecorderConfig) {
        this.aiRecorderConfig = aiRecorderConfig;
        this.webClient = WebClient.builder()
                .baseUrl(aiRecorderConfig.getApiUrl())
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();
    }

    /**
     * 调用AI解析记账文本
     * @param text 待解析的文本（如"昨天买奶茶花了25元"）
     * @return 解析后的记账数据（Map格式，包含金额、分类、时间等）
     */
    public Mono<Map<String, Object>> parseBookkeepingText(String text) {
        // 构造AI接口请求参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("text", text);
        requestBody.put("api_key", aiRecorderConfig.getApiKey());
        requestBody.put("model", aiRecorderConfig.getModel());

        // 调用AI-Recorder接口并返回结果
        return webClient.post()
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {
                });
    }
}

